<!--
	作者：lsd
	时间：2020-2-12
	描述：时段管理
-->

<template>
	<div class="m-view-confirmedPurOrder m-window">
    <!-- 搜索头 -->
		<div class="m-condition">
			<el-row :gutter="5">
				<el-form
					:model="formSearch"
					ref="formSearch"
					label-width="70px"
					:inline-message="true"
					label-position="left"
				>
					<el-col :span="6">
						<el-form-item label="公司" class="rightItem">
							<el-input
								value-key="id"
								v-model="formSearch.companyName"
								placeholder="请输入公司名"
								clearable
							></el-input>
						</el-form-item>
					</el-col>
          <el-col :span="4">
            <el-checkbox @change="search" v-model="formSearch.state">显示停用</el-checkbox>
          </el-col>
				</el-form>
        
				<el-col :span="2"><el-button type="primary" @click="search" >查询</el-button></el-col>
        <el-col :span="2"><el-button type="primary" v-show="!formSearch.state" @click="editBtnClick(0)">新增</el-button></el-col>
        <el-col :span="2"><el-button type="primary" v-show="!formSearch.state" @click="editBtnClick(1)">编辑</el-button></el-col>
        <el-col :span="2"><el-button type="primary" v-show="!formSearch.state" @click="useRegional(0)">停用</el-button></el-col>
        <el-col :span="2"><el-button type="primary" v-show="formSearch.state" @click="useRegional(1)">启用</el-button></el-col>
			</el-row>
		</div>

    <!-- 表单 -->
		<div class="m-agTable m-bottom" v-loading="loading">
			<agGridComponents
        ref="agGridComponent"
				:getGridOptions="gridOptions"
				:getColumnDefs="columnDefs"
        :getRowSelection="'multiple'"
        :isColFit="true"
			></agGridComponents>
		</div>

    <!-- 页脚 -->
		<div class="m-page">
			<el-pagination
				@size-change="handleSizeChange"
				@current-change="handleCurrentChange"
				:current-page="pageInfo.current"
				:page-sizes="[30,50,100,150,200 ]"
				:page-size="pageInfo.pageSize"
				layout="total, sizes, prev, pager, next, jumper"
				:total="pageInfo.total"
			></el-pagination>
		</div>

    <!-- 新增&编辑窗口 -->
    <el-dialog
      :title="titleDia"
      :visible.sync="showDia"
      width="60"
      v-dialogDrag
      :show-close="false"
      :before-close="handleClose"
      :close-on-click-modal="false"
      :close-on-press-escape="false">

      <el-form
        :model="formEdit"
        v-loading="loadingDia"
        ref="formEdit"
        label-width="100px"
        class="demo-ruleForm"
        :rules="rules">
        
        <el-form-item label="公司" prop="companyCode">
          <el-select v-model="formEdit.companyCode" placeholder="请选择公司名">
            <el-option
              v-for="item in optionsCompanyName"
              :key="item.id"
              :label="item.companyName"
              :value="item.companyCode">
            </el-option>
          </el-select>
        </el-form-item>
        <el-row>
          <el-col :span="12">
        <el-form-item label="时段" prop="startTime">
          <el-time-select
            placeholder="起始时间"
            v-model="formEdit.startTime"
            :picker-options="{
              start: '00:00',
              step: '00:15',
              end: '23:45'}">
          </el-time-select>
        </el-form-item>
          </el-col>
          <el-col :span="12">
        <el-form-item prop="endTime">
          <el-time-select
            placeholder="结束时间"
            v-model="formEdit.endTime"
            :picker-options="{
              start: '00:00',
              step: '00:15',
              end: '23:45',
              minTime: formEdit.startTime}">
          </el-time-select>
        </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="最大值" prop="max">
          <el-input v-model="formEdit.max" placeholder="请填写区域"></el-input>
        </el-form-item>
        <el-form-item label="序号" prop="sort">
          <el-input v-model="formEdit.sort" placeholder="请填写序号"></el-input> 
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelClick()">取消</el-button>
        <el-button type="primary" @click="save(false)" :loading="loadingDia">保存</el-button>
        <el-button type="primary" @click="save(true)" :loading="loadingDia">保存并继续</el-button>
      </span>
    </el-dialog>

	</div>
</template>

<script>
import _Api from "@/api";
import localeText from "@/i18n/agGridText";
import agGridComponents from "@/components/agGridComponents.js";

export default {
  components: {
		agGridComponents,
	},
	data () {
		return {
      formSearch: {//查询表
        companyName: '',
        state: false,
      },
      formEdit:{//编辑&新增表
        companyCode: '',
        startTime: '',
        endTime: '',
        max: '',
        sort: '',
      },
      optionsCompanyName:[],
      isEdit: false,//true为编辑,false为新增
      rowData: [], // 表格数据
      //表格参数
      gridOptions:'',
      columnDefs: [],
      //页脚参数
      pageInfo: {
			  pageSize: 30,
			  total: 0,
        current: 1,
      },
      //弹窗参数
      showDia: false,
      titleDia: '',
      //加载参数
      loading: false,//页面的
      loadingDia: false,//弹框的
      rules: {
        companyCode: [{
          required: true,
          trigger: ['blur', 'change'],
          message: "不能为空",
        }],
        startTime: [{
          required: true,
          trigger: ['blur', 'change'],
          message: "不能为空",
        }],
        endTime: [{
          required: true,
          trigger: ['blur', 'change'],
          message: "不能为空",
        }],
        max: [{
          required: true,
          trigger: ['blur', 'change'],
          message: "不能为空",
        }]
      }
		}
	},
	beforeMount () {
		this.gridOptions = {
			context: {
				componentParent: this
			},
			enableColResize: true,
			localeText: localeText,
      suppressRowClickSelection: true,//单元格选中,false为选中整行
		};
		this.columnDefs = [
      { headerName: "公司编码", field: "companyCode", width: 125, 
        checkboxSelection: true, 
        headerCheckboxSelection: true},
      { headerName: "公司名称", field: "companyName", width: 200 },
      { headerName: "时段", field: "region", width: 150 },
      { headerName: "最大值", field: "max", width: 100 },
      { headerName: "序号", field: "sort", width: 75 },
      { headerName: "状态", field: "state", width: 75 },
    ];
    
  },
  mounted(){
    //初始化pageSize
    this.pageInfo.pageSize = 30;
    this.search();
  },
	methods: {
    //查询 
    search(){
      this.loading = true;
      let param = {
        companyName: this.formSearch.companyName,
        pageSize: this.pageInfo.pageSize,
        currentPage: this.pageInfo.current,
        state: this.formSearch.state?0:1,
      };
      _Api
        .searchInterval(param)
        .then(res => {
          this.loading = false;
          if (res.data.code == 1) {
            this.rowData = res.data.rows;
            this.pageInfo.total = res.data.total
            this.$refs.agGridComponent.gridOptions.api.setRowData(this.rowData);
          }else{
            this.$alert(res.data.info, {showClose: false, confirmButton: "确定", customClass: "alertFailure" });
          }
        })
        .catch(err => {
          this.loading = false;
          this.$alert(err.data.info, {showClose: false, confirmButton: "确定", customClass: "alertFailure"});
        });
    },

    //停用&启用 0停用,1启用
    useRegional(val){
      let row = this.$refs.agGridComponent.gridOptions.api.getSelectedRows();
      let idList = [];
      for( let i = 0; i < row.length; i++ ){
        idList.push(row[i].id)
      }
      console.log(idList)
      let param = {
        list: idList
      }
      this.$confirm(`是否${this.formSearch.state?'启用':'停用'}该时段？`, "消息提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          distinguishCancelAndClose: true
      })
      .then(() => {
        this.loading = true
        _Api
          .changeIntervalState(param)
          .then(res => {
            this.loading = false;
            if (res.data.code == 1) {
              this.$alert(`${this.formSearch.state?'启用':'停用'}`, {showClose: false, confirmButton: "确定", customClass: "alertFailure" });
            }else{
              this.$alert(res.data.info, {showClose: false, confirmButton: "确定", customClass: "alertFailure" });
            }
          })
          .catch(err => {
            this.loading = false;
            this.$alert(err.data.info, {showClose: false, confirmButton: "确定", customClass: "alertFailure"});
          });
        
      })   
    },

    //新增&编辑 0新增,1编辑
    editBtnClick(val){
      if( val == 1 ){//编辑
        //单选操作
        let row = this.$refs.agGridComponent.gridOptions.api.getSelectedRows();
        this.isEdit = true;
        if (row.length <= 0) {
          this.$alert("提示：请选择需要停用的时段", {
            showClose: false,
            confirmButtonText: "确定",
            customClass: "alertPrompt"});
          return;
        }
        else if (row.length > 1) {
          this.$alert("提示：请选择一个时段", {
            showClose: false,
            confirmButtonText: "确定",
            customClass: "alertPrompt"});
          return;
        }else{//正戏开始      
          this.optionsCompanyName = [{companyName: row[0].companyName, companyCode: row[0].companyCode}] 
          this.formEdit.companyCode = row[0].companyCode;
          this.formEdit.startTime = row[0].startTime;
          this.formEdit.endTime = row[0].endTime;
          this.formEdit.sort = row[0].sort;
          this.formEdit.id = row[0].id;
        }
      }
      else{//新增
        this.isEdit = false;
        this.getCompanyNameList();//获取公司名字列表
        this.clearForm();//清空表单
      }
      this.titleDia = val==0?'新增时段':'编辑时段';
      this.showDia = true;
    },
    
    //保存&保存并继续(新增的)
    save(continueFlag){
      this.$refs['formEdit'].validate((valid) => {
        if (valid) {
           this.loadingDia = true;
           let param = {
             //companyName: this.formEdit.companyName.companyName,
             companyCode: this.formEdit.companyName.companyCode,
             area: this.formEdit.region,
             sort: parseInt(this.formEdit.sort),
             creatorId:  this.$global.user.id,
             creator: this.$global.user.employeeName//创建人
           }
            _Api
              .saveRegion(param)
              .then(res => {
                this.loadingDia = false;
                if (res.data.code == 1) {
                  this.$message({ message: "保存成功", type: "success" });
                  this.clearForm();//清空表单
                  if(!continueFlag){//保存并继续
                    this.showDia = false;
                  }
                }else{
                  this.$alert(res.data.info, {showClose: false, confirmButton: "确定", customClass: "alertFailure" });
                }
              })
              .catch(err => {
                this.loadingDia = false;
                this.$alert(err.data.info, {showClose: false, confirmButton: "确定", customClass: "alertFailure"});
              });
        }
      })
    },
    
    //保存&保存并继续(编辑的)
    update(continueFlag){
      this.$refs['formEdit'].validate((valid) => {
        if (valid) {
           this.loadingDia = true;
           let param = {
             companyName: this.formEdit.companyName,
             area: this.formEdit.region,
             sort: parseInt(this.formEdit.sort),
             creatorId:  this.$global.user.id,
             creator: this.$global.user.employeeName//创建人
           }
            _Api
              .saveRegion(param)
              .then(res => {
                this.loadingDia = false;
                if (res.data.code == 1) {
                  this.$message({ message: "保存成功", type: "success" });
                  this.clearForm();//清空表单
                  if(!continueFlag){//保存并继续
                    this.showDia = false;
                  }
                }else{
                  this.$alert(res.data.info, {showClose: false, confirmButton: "确定", customClass: "alertFailure" });
                }
              })
              .catch(err => {
                this.loadingDia = false;
                this.$alert(err.data.info, {showClose: false, confirmButton: "确定", customClass: "alertFailure"});
              });
        }
      })
    },

    //获取公司名字列表
    getCompanyNameList(){
      this.loadingDia = true;
      _Api
        .getCompanyList()
        .then(res => {
          this.loadingDia = false;
          if (res.data.code == 1) {
            this.optionsCompanyName = res.data.rows;
          }else{
            this.$alert(res.data.info, {showClose: false, confirmButton: "确定", customClass: "alertFailure" });
          }
        })
        .catch(err => {
          this.loadingDia = false;
          this.$alert(err.data.info, {showClose: false, confirmButton: "确定", customClass: "alertFailure"});
        });
    },
  
    //弹框取消按钮
    cancelClick(){
      this.showDia = false;
      this.clearForm();//清空表单
    },

    //表单清空
    clearForm(){
      if(this.$refs["formEdit"] != null){
        this.$refs.formEdit.resetFields();
       // this.$refs.formEdit.clearValidate();
      }
       
    },

    //一页显示的总条数发送变化时触发
		handleSizeChange(val){
      this.pageInfo.pageSize = val;
      this.search();
    },

    //页数变化时
    handleCurrentChange(val){
      this.pageInfo.current = val;
      this.search();
      //console.log(val,this.pageInfo.pageSize, this.pageInfo.current)
    },

    //弹窗关闭前
    handleClose(){

    }
	}
}
</script>